<template>
  <!-- 将滚动条组件移到外部包裹整个menu组件 -->
  <tui-scrollbar :showHorizontal="false" :showVertical="mode === 'vertical' && !verticalCollapse">
    <nav class="tui-menu" :class="[
      `tui-menu--${mode}`,
      { 'tui-menu--collapse': isVerticalCollapse },
      { 'tui-menu--ellipsis': horizontalEllipsis },
      { 'tui-menu--persistent': persistent },
      popperClass
    ]" @click="handleClick" :style="menuStyle">
      <slot></slot>
    </nav>
  </tui-scrollbar>
</template>

<script setup lang="ts">
import { ref, provide, onMounted, onUnmounted, watch, computed, nextTick } from 'vue';

import type { TuiMenuProps, TuiMenuContext } from './types';
import { useMenuStyles } from './useMenuStyles';
import { AdvancedConditionHandler } from '../../flow';
import { strings } from '../../../';
import { getAllParentIndexes } from '../../tree';

const props = withDefaults(defineProps<TuiMenuProps>(), {
  verticalWidth: '200px',
  verticalCollapseWidth: '56px',
  horizontalHeight: '60px',
  mode: 'vertical',
  verticalCollapse: false,
  horizontalEllipsis: false,
  defaultActive: '',
  defaultOpeneds: () => [],
  uniqueOpened: false,
  menuTrigger: undefined,
  collapseTransition: true,
  popperOffset: 6,
  popperOffsetX: undefined,
  popperOffsetY: undefined,
  showTimeout: 300,
  hideTimeout: 300,
  backgroundColor: 'var(--tui-color-white, #ffffff)',
  textColor: 'var(--tui-text-color-primary, #303133)',
  activeTextColor: 'var(--tui-text-color-active, #409eff)',
  hoverBackgroundColor: 'rgba(0, 0, 0, 0.02)',
  closeOnClickOutside: false,
  popperClass: '',
  persistent: true,
  customStyle: () => ({}),
});

const emit = defineEmits<{
  (e: 'select', index: string): void;
  (e: 'open', index: string): void;
  (e: 'close', index: string): void;
}>();
const activeIndex = ref(props.defaultActive);
const openedMenus = ref<string[]>([...(props.defaultOpeneds || [])]);

const isVerticalCollapse = computed(() => props.verticalCollapse && props.mode === 'vertical');
const effectiveMenuTrigger = computed<'hover' | 'click' | 'contextmenu'>(() => {
  if (props.menuTrigger) return props.menuTrigger;
  if (props.mode === 'horizontal') return 'hover';
  if (props.mode === 'vertical') return props.verticalCollapse ? 'hover' : 'click';
  return 'hover';
});
// 使用菜单样式管理组合式函数
const { cssVars, applyCssVars, getCssVarsObject } = useMenuStyles(props);

// 计算菜单样式，使用组合式函数提供的CSS变量
const menuStyle = computed(() => {
  return { ...getCssVarsObject(), ...props.customStyle };
});

// 提供菜单上下文给子组件
provide<TuiMenuContext>('menuContext', {
  props,
  menuTrigger: effectiveMenuTrigger,
  innerIndex: ref(''),
  menuLevel: ref(1),
  activeIndex,
  openedMenus,
  parentMenuIndexes: ref<string[]>([]),
  handlers: {
    handleSelect,
    handleToggleSubMenu
  },
  styles: {
    cssVars,
    applyCssVars,
    getCssVarsObject
  }
});

// 处理选中事件
function handleSelect(index: string) {
  activeIndex.value = index;
  emit('select', index);
}

// 处理点击事件
function handleClick(event: MouseEvent) {
  event.stopPropagation();
}

// 切换子菜单 - 同时处理点击和hover场景
function handleToggleSubMenu(index: string, parentMenuIndexes: string[] = []) {
  // 检查当前菜单是否已打开
  const isOpen = openedMenus.value.includes(index);
  let effectiveUniqueOpened = props.uniqueOpened;
  if (props.mode === 'vertical' && props.verticalCollapse) {
    effectiveUniqueOpened = true;
  }
  if (props.mode === 'horizontal') {
    effectiveUniqueOpened = true;
  }

  const menuHandler = new AdvancedConditionHandler<boolean, void>()
    // 单菜单模式 && 菜单已打开 - 只关闭当前菜单及其子菜单
    .rule([true, true], () => {
      // 只关闭当前菜单及其子菜单，保留其他菜单
      openedMenus.value = openedMenus.value.filter(openIndex => {
        // 保留不是当前菜单及其子菜单的项目
        const isCurrentOrChild = openIndex === index || openIndex.startsWith(`${index}.`);
        if (isCurrentOrChild) {
          emit('close', openIndex);
        }
        return !isCurrentOrChild;
      });
    })
    // 单菜单模式 && 菜单未打开 - 关闭其他菜单并打开当前菜单及其父菜单
    .rule([true, false], () => {
      // 关闭不相关的菜单，但保留当前菜单及其父菜单
      const menusToKeep = [...parentMenuIndexes, index];

      // 关闭其他打开的菜单并从openedMenus中移除
      openedMenus.value = openedMenus.value.filter(openIndex => {
        if (!menusToKeep.includes(openIndex)) {
          emit('close', openIndex);
          return false;
        }
        return true;
      });

      // 确保当前菜单及其父菜单都处于打开状态
      menusToKeep.forEach(menuIndex => {
        if (!openedMenus.value.includes(menuIndex)) {
          openedMenus.value.push(menuIndex);
          emit('open', menuIndex);
        }
      });
    })
    // 多菜单模式 && 菜单已打开 - 关闭当前菜单
    .rule([false, true], () => {
      // 直接关闭当前菜单，不需要检查activeIndexChain
      openedMenus.value = openedMenus.value.filter(item => item !== index);
      emit('close', index);
    })
    // 多菜单模式 && 菜单未打开 - 打开当前菜单及其所有未打开的父菜单
    .rule([false, false], () => {
      // 确保当前菜单的所有父菜单都处于打开状态
      parentMenuIndexes.forEach(parentIndex => {
        if (!openedMenus.value.includes(parentIndex)) {
          openedMenus.value.push(parentIndex);
          emit('open', parentIndex);
        }
      });

      // 打开当前菜单
      openedMenus.value.push(index);
      emit('open', index);
    })
    // 默认处理 - 通常不会执行到这里
    .otherwise(() => {
      console.warn('Unexpected condition combination for menu toggle');
    })
    .end(() => {
      console.log('是否唯一打开:', effectiveUniqueOpened, '是否已经打开:', isOpen, '切换菜单:', index, '当前打开的菜单:', openedMenus.value, '父菜单索引:', parentMenuIndexes);
    });

  menuHandler.execute([effectiveUniqueOpened, isOpen]);
}

// 处理菜单项激活和展开的公共函数
function updateMenuActiveState(index: string) {
  if (!index) return;

  const parentIndexes = getAllParentIndexes(index, '.');

  // 确保所有父菜单都处于打开状态
  parentIndexes.forEach(parentIndex => {
    if (!openedMenus.value.includes(parentIndex)) {
      openedMenus.value.push(parentIndex);
      emit('open', parentIndex);
    }
  });
};

watch(
  () => props.defaultActive,
  (newValue) => {
    if (newValue) {
      activeIndex.value = strings.chain(newValue).replace('/', '.').trim('.').toString();

      nextTick(() => {
        updateMenuActiveState(activeIndex.value);
      });
    }
  },
  { immediate: true } // 关键：立即执行，处理异步设置的情况
);

// 初始化操作
onMounted(() => {
  // 点击外部关闭菜单
  if (props.closeOnClickOutside) {
    document.addEventListener('click', handleDocumentClick);
  }
});

onUnmounted(() => {
  if (props.closeOnClickOutside) {
    document.removeEventListener('click', handleDocumentClick);
  }
});

// 处理文档点击，当点击菜单外部时关闭菜单
function handleDocumentClick(event: MouseEvent) {
  // 获取当前菜单元素
  const menuElement = document.querySelector('.tui-menu');
  // 检查点击目标是否在菜单内部
  const isClickInside = menuElement?.contains(event.target as Node);

  if (!isClickInside && props.closeOnClickOutside) {
    // 点击了菜单外部，关闭所有展开的子菜单
    openedMenus.value.forEach(index => {
      emit('close', index);
    });
    openedMenus.value = [];
  }
}
</script>

<style lang="scss" scoped>
// 菜单基础样式和所有嵌套样式
.tui-menu {
  width: auto;
  position: relative;
  display: inline-block;
  background-color: var(--tui-menu-background-color);
  color: var(--tui-menu-text-color);
  font-size: var(--tui-font-size-base);
  line-height: 1.5;
  box-sizing: border-box;

  // 垂直菜单样式
  &--vertical {
    display: block;
    border-right: var(--tui-border);
    width: var(--tui-menu-vertical-width);
    transition: width var(--tui-transition-duration),
      transform var(--tui-transition-duration),
      border-right-color var(--tui-transition-duration);
    overflow: visible;
    position: relative;

    &.tui-menu--collapse {
      width: var(--tui-menu-vertical-collapse-width);
      transform-origin: left center;
      overflow: visible;

      :deep(.tui-menu-item__title-text) {
        transition: opacity var(--tui-transition-duration) ease,
          transform var(--tui-transition-duration) ease;
      }
    }

    &:not(.tui-menu--collapse) {
      transform: scaleX(1);

      :deep(.tui-menu-item__title-text) {
        opacity: 1;
        transform: translateX(0);
        transition: opacity var(--tui-transition-duration) ease var(--tui-transition-delay),
          transform var(--tui-transition-duration) ease var(--tui-transition-delay);
      }
    }
  }

  // 水平菜单样式
  &--horizontal {
    display: flex;
    gap: 8px;
    align-items: center;
    height: var(--tui-menu-horizontal-height, 60px);
    border-bottom: var(--tui-border);
    position: relative;
  }

  // 文字省略功能
  &--ellipsis {

    // 为菜单项设置溢出隐藏和宽度限制
    :deep(.tui-menu-item) {
      overflow: hidden;
      max-width: 100%;
    }

    // 为标题内容容器设置flex布局并确保占满空间
    :deep(.tui-menu-item__title-content) {
      display: flex;
      align-items: center;
      width: 100%;
    }

    // 为标题文本设置省略样式并确保占满剩余空间
    :deep(.tui-menu-item__title-text) {
      flex: 1;
      overflow: hidden !important;
      text-overflow: ellipsis !important;
      white-space: nowrap !important;
    }

    // 水平菜单特殊样式
    &.tui-menu--horizontal {
      // 确保菜单本身宽度100%
      width: 100%;

      // 确保下边框正确显示的关键样式
      position: relative;
      display: flex;
      border-bottom: 1px solid var(--tui-border-color);

      // 允许菜单项在空间不足时被压缩以触发省略效果
      :deep(.tui-menu-item) {
        flex-shrink: 1;
        min-width: 0; // 关键：允许flex项在内容溢出时收缩
      }
    }
  }
}

// 菜单项过渡效果
:deep(.tui-menu__item) {
  transition: all 0.3s ease;
  --tui-menu-active-color: v-bind(props.activeTextColor);
  --tui-menu-text-color: var(--tui-menu-text-color);
}
</style>